import { defineStore } from 'pinia'
import type { RouteLocationNormalized } from 'vue-router'

interface TagView extends Partial<RouteLocationNormalized> {
  title?: string
}

interface TagsViewState {
  visitedViews: TagView[]
  cachedViews: string[]
}

export const useTagsViewStore = defineStore('tagsView', {
  state: (): TagsViewState => ({
    visitedViews: [],
    cachedViews: []
  }),
  actions: {
    addView(view: TagView) {
      console.log('是否调用多标签addView:',view)
      if (this.visitedViews.some(v => v.path === view.path)) return
      this.visitedViews.push(
        Object.assign({}, view, {
          title: view.meta?.title || 'unknown'
        })
      )
      if (!view.meta.noCache) {
        this.cachedViews.push(view.name as string)
      }
    },
    delView(view: TagView) {
      const index = this.visitedViews.findIndex(v => v.path === view.path)
      if (index > -1) {
        this.visitedViews.splice(index, 1)
        this.cachedViews = this.cachedViews.filter(name => name !== view.name)
      }
    }
  }
})